/**
 * Created by yuji on 2015/10/28.
 */
'use strict'

var util = require('./util'),
    fs = require('fs'),
    path = require('path').posix,
    ejs = require('ejs');


/**
 * 文件对象
 * @param filePath
 * @constructor
 */
function FileObject(fileName, content){
    this.fileName = fileName;
    this.fileFullName = fileName;
    this.dir = path.dirname(fileName);
    this.template = '';
    this.ext = path.extname(fileName);
    this.type = this.ext=='.css'?'css':'';
    this.encoding = 'utf-8';
    this.content = content;
    this.hash = '';
}

FileObject.genObj = function(filePath){
    let str = fs.readFileSync(filePath);
    return new FileObject(filePath, str);
}

/**
 * 文件对象的预处理点
 * 利用add注册到预处理队列中
 * 调用exe将去除队列执行
 * 最终会更改this.content
 * @type {{add: Function, exe: Function}}
 */
FileObject.prototype.addPreProcess =  function(func){
    this.preProcess = this.preProcess || [];
    this.preProcess.push(func);
};

FileObject.prototype.exePreProcess = function(){
    var func;
    while(func = this.preProcess.shift()){
        this.content = func(this.content);
    }
}

FileObject.prototype.afterPreProcess =  function(func){
    this.afterProcess = this.afterProcess || [];
    this.afterProcess.push(func);
};

FileObject.prototype.exeAfterProcess = function(){
    var func;
    while(func = this.afterProcess.shift()){
        this.content = func(this.content);
    }
}


/**
 * 将文件生成资源表
 */
//@: 感觉这是拖性能的函数
//可以利用模板引擎解决
//先生成模板，之后再render
//map需要这种结构
//{
//   "image/a/b.png":"/image/a/b_dasf134.png"
// }
FileObject.prototype.insertUri = function(rMap){
    //let deps = rMap.deps(this.fileFullName);
    //for(let item of deps){
    //    this.content = this.content.replace(new RegExp(item,"g"),rMap.uri(item));
    //}
    //@TODO 每个文件都生成一次，可能会托性能
    if(this.type ==='css'){
        var flatMap = rMap.toUriMap();
        this.content = ejs.render(this.template,{data:flatMap});
    }

}

/**
 * 生成哈希落到硬盘上
 */
FileObject.prototype.setHash = function(){
    this.hash = util.md5Suffix(this.content);
}

FileObject.prototype.save = function(){
    return util.newFile(this.fileName, this.hash, this.content);
}



module.exports = FileObject;